<template>
    <div class="show">
        <!-- 头部搜索 -->
        <div class="search">
            <el-row>
                <el-col :span="8">
                    <div class="grid-content bg-purple-light">
                        <el-button type="primary" @click="addViews('addfrom')">添加轮播图</el-button>
                        <el-button type="success" @click="rotationView">预览</el-button>
                    </div>
                </el-col>
            </el-row>
        </div>
        <!-- 表格 -->
        <el-table :data="rotationList" style="width: 100%" border stripe>
            <el-table-column align="center" type="index" label="#" width="40"></el-table-column>
            <el-table-column align="center" prop="roname" label="轮播图名称"></el-table-column>
            <el-table-column align="center" prop="rourl" label="略缩图">
                <template slot-scope="scope">
                    <img style="width: 78px;height: 54px;" :src="scope.row.rourl">
                </template>
            </el-table-column>
            <el-table-column align="center" prop="describe" label="描述"></el-table-column>
            <el-table-column align="center" prop="status" label="状态">
                <template slot-scope="scope">
                    <span style="color:red" v-if="scope.row.status == 0"><strong>禁用</strong></span>
                    <span style="color:green" v-if="scope.row.status == 1"><strong>启用</strong></span>
                </template>
            </el-table-column>
            
            <el-table-column align="center" label="操作" width="130">
                <template v-slot="scope">
                    <!-- 修改 -->
                    <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
                        <el-button type="primary" icon="el-icon-edit" circle @click="queryRotationById(scope.row.roid)"></el-button>
                    </el-tooltip>
                    <!-- 删除 -->
                    <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
                        <el-button
                            type="danger"
                            icon="el-icon-delete-solid"
                            circle
                            @click="delRotation(scope.row.roid)"
                        ></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <!-- 轮播图预览-->
        <el-dialog title="轮播图预览" :visible.sync="rotationDialogVisible" width="80%" height="60%">
            <el-carousel :interval="4000" type="card" height="450px">
                <el-carousel-item v-for="item in imagebox" :key="item.roid">
                    <img style="width:750px;height:450px" :src="item.rourl" class="image">
                </el-carousel-item>
            </el-carousel>
        </el-dialog>

        <!-- 添加轮播图弹出层-->
        <el-dialog title="添加轮播图" :visible.sync="adddialogVisible" width="50%">
            <el-form ref="addfrom" :model="addfrom" :rules="rules" class="demo-ruleForm" label-position="right" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="轮播图名称" prop="roname">
                            <el-input v-model="addfrom.roname"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="轮播图描述" prop="describe">
                            <el-input v-model="addfrom.describe"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="addfrom.status" placeholder="请选择">
                                <el-option
                                        v-for="item in statusList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="轮播图" prop="rourl">
                            <!-- 添加URL输入框 -->
                            <el-input v-model="addfrom.rourl" placeholder="输入图片URL"></el-input>
                            
                            <el-upload action 
                                    :drag="true"
                                    :multiple="true"
                                    :on-preview="handlePreview" 
                                    :file-list="fileList"
                                    :http-request="Upload"
                                    :on-success="handleSuccess" 
                                    :on-remove="handleRemove"
                                    :on-exceed="handleExceed"
                                    list-type="picture"
                            >
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text">
                                    或上传图片
                                </div>
                                <div slot="tip" class="el-upload__tip">上传文件大小不能超过 2MB</div>
                            </el-upload>
                            <el-progress v-show="showProgress" :text-inside="true" :stroke-width="15" :percentage="progress"></el-progress>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm('addfrom')">清 空</el-button>
                <el-button type="primary" @click="upForm">新 增</el-button>
            </span>
        </el-dialog>

        <!-- 修改项目信息弹出层 -->
        <el-dialog title="修改项目" :visible.sync="updateDialogVisible" width="50%">
            <el-form ref="updatefrom" :model="updatefrom" :rules="updateRules" class="demo-ruleForm" label-position="right" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="轮播图名称" prop="roname">
                            <el-input v-model="updatefrom.roname"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="轮播图描述" prop="describe">
                            <el-input v-model="updatefrom.describe"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="updatefrom.status" placeholder="请选择">
                                <el-option
                                        v-for="item in statusList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="轮播图" prop="rourl">
                            <!-- 添加URL输入框 -->
                            <el-input v-model="updatefrom.rourl" placeholder="输入新的图片URL"></el-input>
                            
                            <el-upload action 
                                    :drag="true"
                                    :multiple="true"
                                    :on-preview="handlePreview" 
                                    :file-list="fileList"
                                    :http-request="Upload"
                                    :on-success="handleSuccess" 
                                    :on-remove="handleRemove"
                                    :on-exceed="handleExceed" 
                                    list-type="picture"
                            >
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text">
                                    或上传新图片
                                </div>
                                <div slot="tip" class="el-upload__tip">上传文件大小不能超过 2MB</div>
                            </el-upload>
                            <img v-if="updatefrom.rourl" style="width: 78px;height: 54px;" :src="updatefrom.rourl">
                            <el-progress v-show="showProgress" :text-inside="true" :stroke-width="15" :percentage="progress"></el-progress>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="setForm()">修 改</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {client,getFileNameUUID} from '@/method/aliyun.oss.client';
export default {
    name: 'Upload',
    props: {
        limit: {
            type: Number,
            default: 1
        }
    },
    data(){
        return {
            imagebox:[],
            fileList: [], //文件列
            showProgress: false, //进度条的显示
            dataObj: {}, //存签名信息
            progress: 0, //进度条数据
            //轮播图信息
            rotationList:[],
            //添加对话框的显示隐藏
            adddialogVisible: false,
            // 轮播图编辑对话框的显示与隐藏
            updateDialogVisible: false,
            
            rotationDialogVisible:false,
            //修改轮播图表单数据
            updatefrom: {
                roname:'',
                rourl: '',
                describe: '',
                status: ''
            },
            //新增轮播图表单数据
            addfrom: {
                roname:'',
                rourl: '',
                describe: '',
                status: ''
            },
            // 添加表单的验证规则
            rules: {
                roname: [{ required: true, message: '轮播图名称为必填项', trigger: 'blur' }],
                describe: [{ required: true, message: '轮播图描述为必填项', trigger: 'blur' }],
                status: [{ required: true, message: '轮播图状态必填项', trigger: 'blur' }],
                rourl: [{ required: true, message: '请输入图片URL或上传图片', trigger: 'blur' }]
            },
            //修改表单的验证规则
            updateRules: {
                roname: [{ required: true, message: '轮播图名称为必填项', trigger: 'blur' }],
                describe: [{ required: true, message: '轮播图描述为必填项', trigger: 'blur' }],
                status: [{ required: true, message: '轮播图状态必填项', trigger: 'blur' }],
                rourl: [{ required: true, message: '请输入图片URL或上传图片', trigger: 'blur' }]
            },
            //状态
            statusList: [{
                value: '0',
                label: '禁用'
            }, {
                value: '1',
                label: '启用'
            }],
        }
    },
    created() {
        //查询所有轮播图
        this.queryRotation();
    },
    methods: {
        //弹出轮播图预览窗口
        rotationView(){
            this.rotationDialogVisible = true;
        },
        //弹出编辑轮播图窗口
        queryRotationById(roid) {
            // 请求该轮播图的数据
            this.axios
                .get("/api/queryRotationById", {
                    params: {
                        roid: roid
                    }
                })
                .then(response => {
                    this.updatefrom = response.data[0];
                })
                .catch(error => {
                    console.log(error);
                });
            // 展示编辑对话框
            this.updateDialogVisible = true;
        },
        //修改取消
        cancel(){
            this.updateDialogVisible = false;
            this.$message.info("修改操作取消");
        },
        // 提交修改信息
        setForm() {
            this.$refs.updatefrom.validate(valid => {
                if (valid) {
                    this.axios.post("/api/updateRotation", this.updatefrom).then(res => {
                        if (res.data.code !== 200) {
                            return this.$message.error({
                                duration: 800,
                                message: "修改失败"
                            });
                        }else{
                            this.$message.success({
                                duration: 800,
                                message: "修改成功"
                            });
                            // 隐藏对话框
                            this.updateDialogVisible = false; 
                            // 刷新用户列表数据 
                            this.queryRotation()
                            // 清空修改表单数据 
                            this.resetForm('updatefrom');
                        }
                    });
                } else {
                    console.log("表单数据有错误");
                    return false;
                }
            });
        },
        //清空添加用户表单
        resetForm(addfrom) {
            this.$refs[addfrom].resetFields();
        },
        //弹出新增轮播图窗口
        addViews(){
            this.adddialogVisible=true;
        },
        // 提交添加轮播图表单
        upForm() {
            this.$refs.addfrom.validate(valid => {
                if (valid) {
                    this.axios.post("/api/addRotation", this.addfrom).then(res => {
                        if (res.data.code !== 200) {
                            return this.$message.error({
                                duration: 800,
                                message: "添加失败"
                            });
                        }else{
                            this.$message.success({
                                duration: 800,
                                message: "添加成功"
                            });
                            // 隐藏对话框
                            this.adddialogVisible = false; 
                            // 刷新项目列表数据 
                            this.queryRotation()
                            // 清空新增表单数据 
                            this.resetForm('addfrom');
                        }
                    });
                } else {
                    console.log("表单数据有错误");
                    return false;
                }
            });
        },
        //查询所有轮播图
        queryRotation(){
            let _this = this;
            //发送异步请求
            this.axios.get("/api/queryRotation",{
            }).then(res => {
                _this.rotationList = res.data;
                _this.imagebox = res.data;
            });
        },
        // 删除轮播图
        async delRotation(roid) {
            const confirmRes = await this.$confirm(
                "是否确定永久删除该轮播图?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }
            ).catch(err => err);
            // 确认删除返回的是 confirm 字符串
            // 取消删除返回的是 cancel 字符串
            if (confirmRes !== "confirm") {
                return this.$message.error({
                    duration: 800,
                    message: "已取消删除"
                });
            }
            this.axios
                .get("/api/delRotation", {
                    params: {
                        roid: roid
                    }
                })
                .then(res => {
                    if (res.data.code !== 200) {
                        return this.$message.error({
                            duration: 800,
                            message: "删除失败"
                        });
                    }
                    this.$message.success({
                        duration: 800,
                        message: "删除成功"
                    });
                    // 刷新项目列表
                    this.queryRotation();
                });
        },
        /**
         * 文件上传相关方法
         */
        // 文件超出个数限制时的钩子
        handleExceed(files, fileList) {
            this.$message.warning(`每次只能上传 ${this.limit} 个文件`);
        },
        // 点击文件列表中已上传的文件时的钩子
        handlePreview(file) {},
        // 删除文件之前的钩子
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        // 文件列表移除文件时的钩子
        handleRemove(file, fileList) {
            // 移除文件时清空URL
            if (file.response && file.response.name) {
                this.updatefrom.rourl = '';
                this.addfrom.rourl = '';
            }
        },
        // 文件上传成功时的钩子
        handleSuccess(response, file, fileList) {
            this.fileList = fileList;
        },
        //文件上传前的校验
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },

        // 文件上传方法
        Upload(file) {
            const that = this;
            async function multipartUpload() {
                let temporary = file.file.name.lastIndexOf(".");
                let fileNameLength = file.file.name.length;
                let fileFormat = file.file.name.substring(
                    temporary + 1,
                    fileNameLength
                );
                let fileName = getFileNameUUID() + "." + fileFormat;
                client(that.dataObj)
                    .multipartUpload(`image/${fileName}`, file.file, {
                        progress: function(p) {
                            that.showProgress = true;
                            that.progress = Math.floor(p * 100);
                        }
                    })
                    .then(result => {
                        //上传成功返回值，设置URL
                        let aliurl = 'http://mybucket-beijng2.oss-cn-beijing.aliyuncs.com/'+result.name;
                        that.updatefrom.rourl = aliurl;
                        that.addfrom.rourl = aliurl;
                    })
                    .catch(err => {
                        console.log("err:", err);
                    });
            }
            multipartUpload();
        }
    }
};
</script>

<style lang="less" scoped>
.show {
  .search {
    margin-top: 15px;
    .el-input {
      width: 300px;
      margin: 0 30px;
    }
    .el-button {
      width: 100px;
    }
  }
  .el-table {
    margin-top: 40px;
  }
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>